package com.yunshang.ysmall.util;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;

public class SingletonClient {

	private static HttpClient singleHttpClient;
	
//	private static CloseableHttpAsyncClient httpAsyncClient;

	private SingletonClient() {
	}
		
	public static synchronized HttpClient getHttpClient() {
		if (null == singleHttpClient) {
			PoolingHttpClientConnectionManager cm = null;
			HttpRequestRetryHandler myRetryHandler = null;
			// LayeredConnectionSocketFactory sslsf = null;
			// try {
			// sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
			// } catch (NoSuchAlgorithmException e) {
			// e.printStackTrace();
			// }
			try {
				
				TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {  
		            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
		                return new java.security.cert.X509Certificate[] {};  
		            }  
		            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
		            }  
		            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
		            }  
		        } };  
				
				SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()
						.loadTrustMaterial(null, new TrustSelfSignedStrategy())
						.build();
				sslcontext.init(null, trustAllCerts, new java.security.SecureRandom());
				
				HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
						sslcontext, hostnameVerifier);
				Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
						.<ConnectionSocketFactory> create()
						.register("https", sslsf)
						.register("http", new PlainConnectionSocketFactory())
						.build();
				cm = new PoolingHttpClientConnectionManager(
						socketFactoryRegistry);
				cm.setMaxTotal(500);
				cm.setDefaultMaxPerRoute(20);
				
				myRetryHandler = new HttpRequestRetryHandler() {
					@Override
					public boolean retryRequest(IOException arg0, int retryTimes, HttpContext arg2) {
						// TODO Auto-generated method stub
		                return false;  
					}};
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			singleHttpClient = HttpClients.custom().setConnectionManager(cm).setRetryHandler(myRetryHandler)
					.build();
		}
		return singleHttpClient;
	}
	
//	public static synchronized CloseableHttpAsyncClient getCloseableHttpAsyncClient() {
//		if (null == httpAsyncClient) {
//			try {
//				
//				SSLContext sslcontext = org.apache.http.conn.ssl.SSLContexts.custom().useTLS()
//		                .loadTrustMaterial(null, new TrustStrategy()
//		                {
//		                    @Override
//		                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
//		                    {
//		                        return true;
//		                    }
//		                })
//		                .build();
//		        SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAllHostnameVerifier());
//
//		        Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
//		                .register("http", NoopIOSessionStrategy.INSTANCE)
//		                .register("https", sslSessionStrategy)
//		                .build();
//				    
//				// Create I/O reactor configuration
//		        IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
//		                .setIoThreadCount(Runtime.getRuntime().availableProcessors())
//		                .setConnectTimeout(90000)
//		                .setSoTimeout(90000)
//		                .build();
//		        
//		        // Create a custom I/O reactort
//		        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
//		        
//		        // Create a connection manager with custom configuration.
//		        PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
//		        connectionManager.setMaxTotal(1024 * 1024 * 2);
//		        connectionManager.setDefaultMaxPerRoute(1024 * 1024 * 1);
//		        
//		        httpAsyncClient = HttpAsyncClients.custom()
//		        		.setSSLStrategy(sslSessionStrategy)
//		                .setConnectionManager(connectionManager)
//		                //.setDefaultCredentialsProvider(credentialsProvider)
//		                //.setProxy(new HttpHost("127.0.0.1", 7777))
//		                .build();
//		        
//		        httpAsyncClient.start();
//			} catch (Exception x) {
//			    throw new RuntimeException(x);
//			}
//		}
//		return httpAsyncClient;
//	}

	// public CloseableHttpClient getHttpClient() {
	// CloseableHttpClient httpClient = HttpClients.custom()
	// .setConnectionManager(cm).build();
	//
	// /*
	// * CloseableHttpClient httpClient =
	// * HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接
	// */
	// return httpClient;
	// }
}
